<template>
  <div class="investment-stats">
    <!-- B区域：投资统计信息 - 紧凑横向方框布局 -->
    <div class="stats-container">
      <!-- B-1: 총투자금액 -->
      <div class="stat-box investment-box">
        <h3 class="box-title">{{ $t('investmentStats.totalInvestment') }}</h3>
        <div class="box-amount">
          {{ formatKRWCompact(investmentStats.totalInvestment) }}원
        </div>
      </div>

      <!-- B-2: 누적 스테이킹 보상금액 (D: 质押收益NEAR) -->
      <div class="stat-box rewards-box">
        <h3 class="box-title">{{ $t('investmentStats.totalStakingRewards') }}</h3>
        <div class="box-amount-multi">
          <div class="near-amount">{{ formatNearCompact(stakingRewards.totalRewardsNear) }} NEAR</div>
          <div class="krw-amount">{{ formatKRWCompact(stakingRewards.totalRewards) }}원</div>
        </div>
      </div>

      <!-- B-3: 출금 가능한 스테이킹 보상금액 (可提取余额) -->
      <div class="stat-box withdraw-box">
        <h3 class="box-title">{{ $t('investmentStats.availableRewards') }}</h3>
        <div class="box-amount-multi">
          <div class="near-amount">{{ formatNearCompact(stakingRewards.availableRewardsNear) }} NEAR</div>
          <div class="krw-amount">{{ formatKRWCompact(stakingRewards.availableRewards) }}원</div>
        </div>
        <div class="withdraw-action">
          <el-button
            type="primary"
            size="small"
            class="compact-withdraw-btn"
            :loading="isWithdrawing"
            :disabled="stakingRewards.availableRewards <= 0"
            @click="handleWithdraw"
          >
            {{ isWithdrawing ? $t('investmentStats.processing') : $t('investmentStats.withdraw') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 출금 확인 다이얼로그 -->
    <el-dialog
      v-model="showWithdrawDialog"
      :title="$t('investmentStats.withdrawTitle')"
      width="450"
      align-center
    >
      <div class="withdraw-dialog">
        <div class="withdraw-info">
          <p>{{ $t('investmentStats.withdrawAmount') }}</p>
          <div class="withdraw-amount">
            {{ formatKRW(stakingRewards.availableRewards) }}
          </div>
        </div>

        <!-- 金额输入区 -->
        <div class="withdraw-input-section">
          <label class="input-label">{{ $t('investmentStats.withdrawAmountInput') }}</label>
          <el-input
            v-model.number="withdrawAmount"
            type="number"
            :placeholder="$t('investmentStats.enterAmount')"
            size="large"
            class="amount-input"
          >
            <template #append>
              <el-button
                type="primary"
                @click="withdrawAmount = Math.floor(stakingRewards.availableRewards)"
              >
                {{ $t('investmentStats.maxAmount') }}
              </el-button>
            </template>
          </el-input>
          <p class="input-hint">
            {{ $t('investmentStats.minWithdrawError') }}
          </p>
        </div>

        <div class="withdraw-note">
          <el-alert
            :title="$t('investmentStats.withdrawNoticeTitle')"
            type="info"
            :closable="false"
            show-icon
          >
            <p>{{ $t('investmentStats.withdrawNotice1') }}</p>
            <p>{{ $t('investmentStats.withdrawNotice2') }}</p>
            <p>{{ $t('investmentStats.withdrawNotice3') }}</p>
          </el-alert>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showWithdrawDialog = false">{{ $t('dashboard.cancel') }}</el-button>
          <el-button
            type="primary"
            :loading="isWithdrawing"
            @click="confirmWithdraw"
          >
            {{ $t('investmentStats.withdrawConfirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { walletApiService, type InvestmentStats } from '@/services/walletApi'
import { stakingApiService, type StakingRewards } from '@/services/stakingApi'
import { formatKRW, formatPercentage } from '@/utils/currency'
import { eventBus, Events } from '@/utils/eventBus'
import { api } from '@/utils/request'

const { t: $t } = useI18n()
const router = useRouter()

// 添加紧凑格式化函数 - 保留千分位逗号
const formatKRWCompact = (amount: number): string => {
  return formatKRW(amount)
}

// 格式化NEAR数量
const formatNearCompact = (amount: number): string => {
  return amount.toFixed(4)
}

const investmentStats = ref<InvestmentStats>({
  totalInvestment: 0,
  currentValue: 0,
  totalReturn: 0,
  returnRate: 0,
  dayChange: 0,
  dayChangeRate: 0
})

const stakingRewards = ref<StakingRewards>({
  totalRewards: 0,
  totalRewardsNear: 0,
  availableRewards: 0,
  availableRewardsNear: 0,
  lockedRewards: 0,
  dailyRewards: 0,
  dailyRewardsNear: 0,
  apy: 0,
  dailyRate: 0,
  stakingPeriod: 0
})

const isWithdrawing = ref(false)
const showWithdrawDialog = ref(false)
const withdrawAmount = ref<number>(0)

const loadData = async () => {
  try {
    const [investmentData, rewardsData] = await Promise.all([
      walletApiService.getInvestmentStats(),
      stakingApiService.getStakingRewards()
    ])

    investmentStats.value = investmentData
    stakingRewards.value = rewardsData
  } catch (error) {
    console.error('데이터 로드 실패:', error)
    ElMessage.error('데이터 로드에 실패했습니다')
  }
}

const handleWithdraw = () => {
  if (stakingRewards.value.availableRewards < 3000) {
    ElMessage.warning($t('investmentStats.minWithdrawError'))
    return
  }
  // 默认提现金额为全部可用余额
  withdrawAmount.value = Math.floor(stakingRewards.value.availableRewards)
  showWithdrawDialog.value = true
}

const confirmWithdraw = async () => {
  try {
    // 验证提现金额
    const amount = Math.floor(withdrawAmount.value)
    const maxAmount = Math.floor(stakingRewards.value.availableRewards)

    if (amount < 3000) {
      ElMessage.warning($t('investmentStats.minWithdrawError'))
      return
    }

    if (amount > maxAmount) {
      ElMessage.warning($t('investmentStats.invalidAmountRange', { max: formatKRW(maxAmount) }))
      return
    }

    isWithdrawing.value = true

    // 调用统一的提现接口 /api/withdraw/apply
    const response = await api.post('/api/withdraw/apply', {
      amount
    })

    if (response.success) {
      ElMessage.success({
        message: $t('investmentStats.withdrawSuccess', { txHash: response.data.id }),
        duration: 5000
      })

      // 출금 후 데이터 업데이트
      await loadData()
      showWithdrawDialog.value = false

      // 发出提现成功事件
      eventBus.emit(Events.WITHDRAW_SUCCESS, {
        amount: amount
      })

      // 跳转到提现历史页面
      setTimeout(() => {
        router.push('/app/withdraw/history')
      }, 1500)
    }
  } catch (error) {
    console.error('출금 실패:', error)
    ElMessage.error('출금 작업에 실패했습니다')
  } finally {
    isWithdrawing.value = false
  }
}

onMounted(async () => {
  await loadData()

  // 监听数据刷新事件
  eventBus.on(Events.REFRESH_INVESTMENT_DATA, loadData)
  eventBus.on(Events.REFRESH_WALLET_DATA, loadData)
  eventBus.on(Events.UPBIT_PURCHASE_SUCCESS, loadData)
  eventBus.on(Events.WITHDRAW_SUCCESS, loadData)
})

onUnmounted(() => {
  // 清理事件监听
  eventBus.off(Events.REFRESH_INVESTMENT_DATA, loadData)
  eventBus.off(Events.REFRESH_WALLET_DATA, loadData)
  eventBus.off(Events.UPBIT_PURCHASE_SUCCESS, loadData)
  eventBus.off(Events.WITHDRAW_SUCCESS, loadData)
})
</script>

<style scoped lang="scss">
.investment-stats {
  .stats-container {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .stat-box {
    flex: 1 1 0;
    background: white;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    padding: 20px 16px;
    text-align: center;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    min-height: 140px;
    display: flex;
    flex-direction: column;
    justify-content: center;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
      border-color: #3b82f6;
    }

    &.investment-box {
      border-color: #ddd6fe;
      background: linear-gradient(135deg, #faf5ff 0%, #f3e8ff 100%);
      
      &:hover {
        border-color: #8b5cf6;
      }
    }

    &.rewards-box {
      border-color: #fce7f3;
      background: linear-gradient(135deg, #fdf2f8 0%, #fce7f3 100%);
      
      &:hover {
        border-color: #ec4899;
      }
    }

    &.withdraw-box {
      border-color: #cffafe;
      background: linear-gradient(135deg, #f0fdfa 0%, #cffafe 100%);
      
      &:hover {
        border-color: #06b6d4;
      }
    }

    .box-title {
      font-size: 14px;
      font-weight: 600;
      color: #374151;
      margin: 0 0 12px 0;
      line-height: 1.3;
    }

    .box-amount {
      font-size: 30px; // C需求: 增大字体 (24px + 6px)
      font-weight: 700;
      color: #1f2937;
      margin: 0 0 12px 0;
      line-height: 1.2;
      padding: 8px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(0, 0, 0, 0.05);
    }

    // 新增: 双行金额显示样式 (NEAR + KRW)
    .box-amount-multi {
      display: flex;
      flex-direction: column;
      gap: 6px;
      margin: 0 0 12px 0;
      padding: 10px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(0, 0, 0, 0.05);

      .near-amount {
        font-size: 22px; // C需求: 增大字体 (16px + 6px)
        font-weight: 700;
        color: #0369a1;
        line-height: 1.2;
      }

      .krw-amount {
        font-size: 18px;
        font-weight: 600;
        color: #64748b;
        line-height: 1.2;
      }
    }

    .withdraw-action {
      margin-top: auto;

      .compact-withdraw-btn {
        padding: 6px 16px;
        height: 32px;
        border-radius: 16px;
        font-weight: 600;
        font-size: 12px;
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        border: none;
        box-shadow: 0 2px 8px rgba(6, 182, 212, 0.3);

        &:hover {
          background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(6, 182, 212, 0.4);
        }
      }
    }
  }

  .withdraw-dialog {
    .withdraw-info {
      text-align: center;
      margin-bottom: 20px;

      p {
        color: #64748b;
        margin-bottom: 8px;
      }

      .withdraw-amount {
        font-size: 24px;
        font-weight: 700;
        color: #1a202c;
      }
    }

    .withdraw-input-section {
      margin-bottom: 20px;

      .input-label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
      }

      .amount-input {
        :deep(.el-input__inner) {
          text-align: center;
          font-size: 16px;
          font-weight: 600;
        }

        :deep(.el-input-group__append) {
          background: #7c3aed;
          border-color: #7c3aed;

          .el-button {
            background: transparent;
            border: none;
            color: white;
            font-weight: 600;

            &:hover {
              background: rgba(255, 255, 255, 0.1);
            }
          }
        }
      }

      .input-hint {
        margin-top: 6px;
        font-size: 12px;
        color: #64748b;
        text-align: center;
      }
    }

    .withdraw-note {
      :deep(.el-alert) {
        .el-alert__content {
          p {
            margin: 4px 0;
            font-size: 13px;
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

@media (max-width: 1180px) {
  .investment-stats {
    .stats-container {
      gap: 12px;
    }

    .stat-box {
      padding: 20px 14px;

      .box-title {
        font-size: 13px;
      }

      .box-amount {
        font-size: 22px;
      }
    }
  }
}

@media (max-width: 900px) {
  .investment-stats {
    .stats-container {
      flex-direction: column;
    }

    .stat-box {
      width: 100%;
      max-width: 100%;
      align-items: center;
      text-align: center;

      .withdraw-action {
        width: 100%;

        .compact-withdraw-btn {
          width: 100%;
        }
      }
    }
  }
}

@media (max-width: 600px) {
  .investment-stats {
    .stat-box {
      padding: 18px 14px;

      .box-title {
        font-size: 12px;
      }

      .box-amount {
        font-size: 20px;
      }
    }
  }
}
</style>
